package com.example.ccmusic

import android.content.ContentUris
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.net.Uri
import android.util.Log
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream


object ImageUtils {
    private const val TAG = "ImageUtils"
    private val albumArtUri: Uri = Uri.parse("content://media/external/audio/albumart")

    fun getBitmapByAlbumId(context: Context, albumId: Long): Bitmap? {
        var inputStream: InputStream? = null
        try {
            val contentResolver = context.contentResolver
            val uri = ContentUris.withAppendedId(albumArtUri, albumId)
            inputStream = contentResolver.openInputStream(uri)
            val options = BitmapFactory.Options()
            // 原始大小
            options.inSampleSize = computeSampleSize(options, 600)
            //
            options.inJustDecodeBounds = false
            options.inPreferredConfig = Bitmap.Config.ARGB_8888
            return BitmapFactory.decodeStream(inputStream, null, options)
        } catch (e: FileNotFoundException) {
            // return default
            return null
        } finally {
            try {
                inputStream?.close()
            } catch (e: IOException) {
                Log.d(TAG, "getBitmapByAlbumId: close error")
            }
        }
    }

    /**
     * 对图片进行合适的缩放
     * @param options options设置
     * @param target 类型
     * @return size
     */
    private fun computeSampleSize(options: BitmapFactory.Options, target: Int): Int {
        val w = options.outWidth
        val h = options.outHeight
        val candidateW = w / target
        val candidateH = h / target
        var candidate = Math.max(candidateW, candidateH)
        if (candidate == 0) {
            return 1
        }
        if (candidate > 1) {
            if (w > target && w / candidate < target) {
                candidate -= 1
            }
        }
        if (candidate > 1) {
            if (h > target && h / candidate < target) {
                candidate -= 1
            }
        }
        return candidate
    }
}